package com.weifly.jettycn.control;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.weifly.jettycn.JettycnUtil;
import com.weifly.jettycn.domain.Catalog;
import com.weifly.jettycn.domain.Project;
import com.weifly.jettycn.domain.Release;
import com.weifly.jettycn.service.IProjectService;
import com.weifly.jettycn.service.ProjectService;
import com.weifly.jettycn.util.CallResult;
import com.weifly.jettycn.util.PageInfo;
import com.weifly.jettycn.util.QueryInfo;
import com.weifly.jettycn.util.TreeNode;

/**
 * 项目主页面
 * 
 * @author wei
 * @date 2011-10-05
 */
@Controller
public class ProjectLogic extends AbstractLogic {
	
	private IProjectService projectService;

	public void setProjectService(IProjectService projectService) {
		this.projectService = projectService;
	}

	/**
	 * 主页面
	 */
	@RequestMapping("/project/main.do")
	public ModelAndView main(HttpServletRequest request, HttpServletResponse response) {
		// 项目分类树
		List<TreeNode> catalogList = this.projectService.getCatalogCache();
		request.setAttribute("catalogList", catalogList);
		// 当前类别
		List<TreeNode> catalogLevels = new ArrayList<TreeNode>();
		request.setAttribute("catalogLevels", catalogLevels);
		// 项目列表
		QueryInfo qi = JettycnUtil.createQueryInfo(request);
		String cid = request.getParameter("catalog");
		List<String> cl = null;
		if(StringUtils.isNotBlank(cid)){
			List<TreeNode> nodeList = this.projectService.getCatalogLevel(cid);
			catalogLevels.addAll(nodeList);
			if(nodeList.size()>0){
				TreeNode tn = nodeList.get(nodeList.size()-1);
				cl = new ArrayList<String>();
				ProjectService.countCatalog(cl, tn);
			}
		}
		PageInfo pageInfo = this.projectService.queryProjectList(qi, cl);
		request.setAttribute("projectList", pageInfo);
		
		return new ModelAndView("project/main");
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping("/project/detail.do")
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response) {
		// 项目分类树
		List<TreeNode> catalogList = this.projectService.getCatalogCache();
		request.setAttribute("catalogList", catalogList);
		// 当前项目
		String pid = request.getParameter("project");
		Project project = this.projectService.getProject(pid);
		request.setAttribute("project", project);
		// 版本信息
		PageInfo releaseList = this.projectService.queryReleaseList(pid, JettycnUtil.createQueryInfo(request));
		request.setAttribute("releaseList", releaseList);
		// 当前类别
		List<TreeNode> catalogLevels = new ArrayList<TreeNode>();
		if(StringUtils.isNotBlank(project.getCatalogid())){
			List<TreeNode> nodeList = this.projectService.getCatalogLevel(project.getCatalogid());
			catalogLevels.addAll(nodeList);
		}
		request.setAttribute("catalogLevels", catalogLevels);
		
		return new ModelAndView("project/detail");
	}
	
	/**
	 * 类别列表
	 */
	@RequestMapping("/console/project/catalogList.do")
	public ModelAndView consoleCatalogList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 项目分类树
		List<TreeNode> catalogList = this.projectService.getCatalogCache();
		List<Map<String, Object>> cl = new ArrayList<Map<String, Object>>();
		for(TreeNode node : catalogList){
			dealTreeNode(node, cl);
		}
		request.setAttribute("catalogList", cl);
		
		return new ModelAndView("console/project/catalogList");
	}
	
	private void dealTreeNode(TreeNode node, List<Map<String, Object>> cl){
		Catalog cata = (Catalog)node.getTarget();
		Map<String, Object> rec = new HashMap<String, Object>();
		rec.put("id", cata.getCatalogid());
		rec.put("name", cata.getName());
		if(cata.isLeaf()){
			rec.put("leaf", "叶子节点");
		}else{
			rec.put("leaf", "");
		}
		if(cata.getOrder()==0){
			rec.put("order", "");
		}else{
			rec.put("order", String.valueOf(cata.getOrder()));
		}
		StringBuilder sb = new StringBuilder();
		TreeNode tn = node;
		while(tn.getParent()!=null){
			Catalog pc = (Catalog)tn.getParent().getTarget();
			sb.insert(0, pc.getName() + " -- ");
			tn = tn.getParent();
		}
		rec.put("parent", sb.toString());
		
		cl.add(rec);
		
		if(node.getChildList()!=null && !node.getChildList().isEmpty()){
			for(TreeNode sub : node.getChildList()){
				dealTreeNode(sub, cl);
			}
		}
	}
	
	/**
	 * 添加类别
	 */
	@RequestMapping("/console/project/addCatalog.do")
	public ModelAndView consoleAddCatalog(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 项目分类树
		List<TreeNode> catalogList = this.projectService.getCatalogCache();
		request.setAttribute("catalogList", catalogList);
		
		return new ModelAndView("console/project/addCatalog");
	}
	
	/**
	 * 加载子类别
	 */
	@RequestMapping("/console/project/loadSubCatalog.do")
	public ModelAndView consoleLoadSubCatalog(HttpServletRequest request, HttpServletResponse response) {
		CallResult result = new CallResult();
		// 查找catalog
		String catalogid = request.getParameter("catalogid");
		List<TreeNode> nodeList = projectService.getCatalogLevel(catalogid);
		// 如果catalog不存在，则返回错误
		if(nodeList.isEmpty()){
			result.setSuccess(false);
			result.addMessage("项目类别不存在：" + catalogid);
			this.writeAjaxObject(response, result);
			return null;
		}
		TreeNode node = nodeList.get(nodeList.size()-1);
		// 生成数据并返回
		List<Map<String, Object>> recList = new ArrayList<Map<String, Object>>();
		if(node.getChildList()!=null){
			for(TreeNode subNode : node.getChildList()){
				Catalog subCata = (Catalog)subNode.getTarget();
				Map<String, Object> rec = new HashMap<String, Object>();
				rec.put("id", subCata.getCatalogid());
				rec.put("name", subCata.getName());
				recList.add(rec);
			}
		}
		
		result.setParam(recList);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	/**
	 * 插入子类别
	 */
	@RequestMapping("/console/project/insertCatalog.do")
	public ModelAndView consoleInsertCatalog(HttpServletRequest request, HttpServletResponse response) {
		Catalog cata = this.populateCatalog(request);
		CallResult result = this.projectService.insertCatalog(cata);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	private Catalog populateCatalog(HttpServletRequest request){
		Catalog cata = new Catalog();
		cata.setName(request.getParameter("catalog_name"));
		String clevel1 = request.getParameter("catalog_level1");
		String clevel2 = request.getParameter("catalog_level2");
		if(clevel2!=null && !"-1".equals(clevel2)){
			cata.setParentid(clevel2);
		}else if(clevel1!=null && !"-1".equals(clevel1)){
			cata.setParentid(clevel1);
		}
		String cleaf = request.getParameter("catalog_leaf");
		cata.setLeaf(Boolean.parseBoolean(cleaf));
		try{
			String corder = request.getParameter("catalog_order");
			cata.setOrder(Integer.parseInt(corder));
		}catch(NumberFormatException ne){
		}
		return cata;
	}
	
	/**
	 * 刷新类别缓存
	 */
	@RequestMapping("/console/project/reloadCatalogCache.do")
	public ModelAndView consoleReloadCatalogCache(HttpServletRequest request, HttpServletResponse response) {
		this.projectService.reloadCatalogCache();
		this.writeAjaxObject(response, new CallResult());
		return null;
	}
	
	/**
	 * 修改类别
	 */
	@RequestMapping("/console/project/editCatalog.do")
	public ModelAndView consoleEditCatalog(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("catalog");
		Catalog cata = this.projectService.getCatalog(id);
		request.setAttribute("catalog", cata);
		
		List<TreeNode> level1List = this.projectService.getCatalogCache();
		List<TreeNode> level2List = new ArrayList<TreeNode>();
		String level1Value = "";
		String level2Value = "";
		if(cata.getParentid()!=null && cata.getParentid().trim().length()>0){
			List<TreeNode> levels = this.projectService.getCatalogLevel(cata.getParentid());
			TreeNode node1 = levels.get(0);
			if(node1.getChildList()!=null){
				level2List.addAll(node1.getChildList());
			}
			// 处理level1Value和level2Value
			level1Value = ((Catalog)node1.getTarget()).getCatalogid();
			if(levels.size()>1){
				level2Value = ((Catalog)levels.get(1).getTarget()).getCatalogid();
			}
		}
		request.setAttribute("level1List", level1List);
		request.setAttribute("level2List", level2List);
		request.setAttribute("level1Value", level1Value);
		request.setAttribute("level2Value", level2Value);
		
		return new ModelAndView("console/project/editCatalog");
	}

	/**
	 * 更新类别
	 */
	@RequestMapping("/console/project/updateCatalog.do")
	public ModelAndView consoleUpdateCatalog(HttpServletRequest request, HttpServletResponse response) {
		Catalog cata = this.populateCatalog(request);
		cata.setCatalogid(request.getParameter("catalog_id"));
		CallResult result = this.projectService.updateCatalog(cata);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	/**
	 * 删除类别
	 */
	@RequestMapping("/console/project/deleteCatalog.do")
	public ModelAndView consoleDeleteCatalog(HttpServletRequest request, HttpServletResponse response) {
		String cid = request.getParameter("catalog");
		CallResult result = this.projectService.deleteCatalog(cid);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	/**
	 * 项目列表
	 */
	@RequestMapping("/console/project/projectList.do")
	public ModelAndView consoleProjectList(HttpServletRequest request, HttpServletResponse response) {
		// 项目列表
		QueryInfo qi = JettycnUtil.createQueryInfo(request);
		PageInfo pageInfo = this.projectService.queryProjectList(qi, null);
		request.setAttribute("proPageInfo", pageInfo);
		
		return new ModelAndView("console/project/projectList");
	}
	
	/**
	 * 添加项目
	 */
	@RequestMapping("/console/project/addProject.do")
	public ModelAndView consoleAddProject(HttpServletRequest request, HttpServletResponse response) {
		// 项目分类树
		List<TreeNode> catalogList = this.projectService.getCatalogCache();
		request.setAttribute("catalogList", catalogList);
		
		return new ModelAndView("console/project/addProject");
	}
	
	/**
	 * 插入项目
	 */
	@RequestMapping("/console/project/insertProject.do")
	public ModelAndView consoleInsertProject(HttpServletRequest request, HttpServletResponse response) {
		Project pro = this.populateProject(request);
		CallResult result = this.projectService.insertProject(pro);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	private Project populateProject(HttpServletRequest request){
		Project pro = new Project();
		pro.setName(request.getParameter("project_name"));
		pro.setHomepage(request.getParameter("project_homepage"));
		pro.setAuthor(request.getParameter("project_author"));
		pro.setDescription(request.getParameter("project_desc"));
		
		String plevel1 = request.getParameter("project_level1");
		String plevel2 = request.getParameter("project_level2");
		String plevel3 = request.getParameter("project_level3");
		if(plevel3!=null && !"-1".equals(plevel3)){
			pro.setCatalogid(plevel3);
		}else if(plevel2!=null && !"-1".equals(plevel2)){
			pro.setCatalogid(plevel2);
		}else if(plevel1!=null && !"-1".equals(plevel1)){
			pro.setCatalogid(plevel1);
		}
		
		return pro;
	}
	
	/**
	 * 编辑项目
	 */
	@RequestMapping("/console/project/editProject.do")
	public ModelAndView consoleEditProject(HttpServletRequest request, HttpServletResponse response) {
		String pid = request.getParameter("project");
		Project project = this.projectService.getProject(pid);
		request.setAttribute("project", project);
		
		List<TreeNode> level1List = this.projectService.getCatalogCache();
		List<TreeNode> level2List = new ArrayList<TreeNode>();
		List<TreeNode> level3List = new ArrayList<TreeNode>();
		String level1Value = "";
		String level2Value = "";
		String level3Value = "";
		if(StringUtils.isNotBlank(project.getCatalogid())){
			List<TreeNode> levels = this.projectService.getCatalogLevel(project.getCatalogid());
			if(levels.size()>0){
				level1Value = ((Catalog)levels.get(0).getTarget()).getCatalogid();
				if(levels.get(0).getChildList()!=null){
					level2List.addAll(levels.get(0).getChildList());
				}
			}
			if(levels.size()>1){
				level2Value = ((Catalog)levels.get(1).getTarget()).getCatalogid();
				if(levels.get(1).getChildList()!=null){
					level3List.addAll(levels.get(1).getChildList());
				}
			}
			if(levels.size()>2){
				level3Value = ((Catalog)levels.get(2).getTarget()).getCatalogid();
			}
		}
		request.setAttribute("level1List", level1List);
		request.setAttribute("level2List", level2List);
		request.setAttribute("level3List", level3List);
		request.setAttribute("level1Value", level1Value);
		request.setAttribute("level2Value", level2Value);
		request.setAttribute("level3Value", level3Value);
		
		return new ModelAndView("console/project/editProject");
	}
	
	/**
	 * 更新项目
	 */
	@RequestMapping("/console/project/updateProject.do")
	public ModelAndView consoleUpdateProject(HttpServletRequest request, HttpServletResponse response) {
		Project project = this.populateProject(request);
		project.setPrjid(request.getParameter("project_id"));
		CallResult result = this.projectService.updateProject(project);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	/**
	 * 删除项目
	 */
	@RequestMapping("/console/project/deleteProject.do")
	public ModelAndView consoleDeleteProject(HttpServletRequest request, HttpServletResponse response) {
		String pid = request.getParameter("projectid");
		CallResult result = this.projectService.deleteProject(pid);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	/**
	 * release列表
	 */
	@RequestMapping("/console/project/releaseList.do")
	public ModelAndView consoleReleaseList(HttpServletRequest request, HttpServletResponse response) {
		String pid = request.getParameter("project");
		QueryInfo queryInfo = JettycnUtil.createQueryInfo(request);
		PageInfo releaseList = this.projectService.queryReleaseList(pid, queryInfo);
		request.setAttribute("releaseList", releaseList);
		return new ModelAndView("console/project/releaseList");
	}
	
	/**
	 * 新建release
	 */
	@RequestMapping("/console/project/addRelease.do")
	public ModelAndView consoleAddRelease(HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView("console/project/addRelease");
	}
	
	/**
	 * 插入release
	 */
	@RequestMapping("/console/project/insertRelease.do")
	public ModelAndView consoleInsertRelease(HttpServletRequest request, HttpServletResponse response) {
		Release rel = populateRelease(request);
		CallResult result = this.projectService.insertRelease(rel);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	/**
	 * 编辑release
	 */
	@RequestMapping("/console/project/editRelease.do")
	public ModelAndView consoleEditRelease(HttpServletRequest request, HttpServletResponse response) {
		String releaseid = request.getParameter("release");
		Release rel = this.projectService.getRelease(releaseid);
		request.setAttribute("release", rel);
		return new ModelAndView("console/project/editRelease");
	}
	
	/**
	 * 更新release
	 */
	@RequestMapping("/console/project/updateRelease.do")
	public ModelAndView consoleUpdateRelease(HttpServletRequest request, HttpServletResponse response) {
		Release rel = this.populateRelease(request);
		String releaseid = request.getParameter("release_releaseid");
		rel.setReleaseid(releaseid);
		CallResult result = this.projectService.updateRelease(rel);
		this.writeAjaxObject(response, result);
		return null;
	}
	
	private Release populateRelease(HttpServletRequest request){
		Release rel = new Release();
		rel.setPrjid(request.getParameter("release_prjid"));
		rel.setVersion(request.getParameter("release_version"));
		String publicdate = request.getParameter("release_publishdate");
		try {
			rel.setPublishdate(JettycnUtil.parseDate(publicdate));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		rel.setDesc(request.getParameter("release_desc"));
		return rel;
	}
	
	/**
	 * 删除release
	 */
	@RequestMapping("/console/project/deleteRelease.do")
	public ModelAndView consoleDeleteRelease(HttpServletRequest request, HttpServletResponse response) {
		String releaseid = request.getParameter("releaseid");
		CallResult result = this.projectService.deleteRelease(releaseid);
		this.writeAjaxObject(response, result);
		return null;
	}
}
